# coding=utf-8
import os
import time

from django.conf.urls import url
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from apps.payment.mix_pay import mix_pay_handler
from apps.student.handlers import (loginout, setting, absorbed)


from apps.student.share import app_logger
from project.settings import USER_LEVEL

Error_Not_Login = JsonResponse({
    'retcode': 302,
    'msg': '未登录',
    'redirect': '/student/login/login.html',
})
Error_Not_Student = JsonResponse({
    'retcode': 1,
    'msg': '请以学生帐号登录',
    'redirect': '/student/login/login.html',
})

mobile_Error_Not_Login = JsonResponse({
    'retcode': 99,
    'msg': '未登录',
})
mobile_Error_Not_Student = JsonResponse({
    'retcode': 100,
    'msg': '请以正确帐号登录',
})


def checkuserisstudentforapicaller(request, *args, **kwargs):
    execStartTime = time.time()
    if 'ut' not in request.session:
        return Error_Not_Login

    # if request.session['ut'] != USER_TYPE.STDUENT:
    #     return Error_Not_Student

    realCall = kwargs.pop('_viewFunc')
    ret = realCall(request, *args, **kwargs)

    execEndTime = time.time()
    # 所有大于100ms的操作，产生日志告警
    opTime = execEndTime - execStartTime
    if opTime > 0.1:
        app_logger.warning('!! op takes %s seconds : function:%s %s  ' % (opTime, request.method, request.path))

    return ret


def mobile_CheckUserForApiCaller(request, *args, **kwargs):
    ut = kwargs.pop('ut', [])
    if len(ut) > 0:
        if 'ut' not in request.session:
            return mobile_Error_Not_Login

        if request.session['ut'] not in ut:
            return mobile_Error_Not_Student

    execStartTime = time.time()

    realCall = kwargs.pop('_viewFunc')
    ret = realCall(request, *args, **kwargs)

    execEndTime = time.time()
    # 所有大于100ms的操作，产生日志告警
    opTime = execEndTime - execStartTime
    if opTime > 0.1:
        app_logger.warning('!! op takes %s seconds : function:%s %s  ' % (opTime, request.method, request.path))

    return ret


urlpatterns_api = []


def addPreCheck(urlpatterns, checkFunC):
    for pattern in urlpatterns:
        urlRegx = pattern[0]
        if type(urlRegx) != list:
            urlRegList = [urlRegx]
        else:
            urlRegList = urlRegx

        viewFunc = pattern[1]
        if len(pattern) == 2:
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, {'_viewFunc': viewFunc}))

        elif len(pattern) == 3:
            otherPara = pattern[2]
            otherPara['_viewFunc'] = viewFunc
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, otherPara))
        else:
            # print '!!unsupported url format : %s' % pattern
            os._exit(3)


mobile_urlpatterns_api = []


def mobile_addPreCheck(urlpatterns, checkFunC, ut=[]):
    checkFunC = csrf_exempt(checkFunC)
    for pattern in urlpatterns:
        urlRegx = pattern[0]
        if type(urlRegx) != list:
            urlRegList = [urlRegx]
        else:
            urlRegList = urlRegx

        viewFunc = pattern[1]
        if len(pattern) == 2:
            for one in urlRegList:
                mobile_urlpatterns_api.append(url(one, checkFunC, {'_viewFunc': viewFunc, 'ut': ut}))

        elif len(pattern) == 3:
            otherPara = pattern[2]
            otherPara['_viewFunc'] = viewFunc
            otherPara['ut'] = ut
            for one in urlRegList:
                mobile_urlpatterns_api.append(url(one, checkFunC, otherPara))
        else:
            # print '!!unsupported url format : %s' % pattern
            os._exit(3)


urlpatterns_api_agrs = [
    # ([r'^yj_students/$',
    #   r'^yj_students/(?P<resource_id>\w+)/$'],
    #  student.student_handler.dispatch),
    # 
    # ([r'^yj_products/$',
    #   r'^yj_products/(?P<resource_id>\w+)/$'],
    #  product.product_handler.dispatch),
    # 
    # ([r'^product_yjmemeber/$',
    #   r'^product_yjmemeber/(?P<resource_id>\w+)/$'],
    #  product_yjmemeber.handler.dispatch),
    # 
    # ([r'^yj_lessons/$',
    #   r'^yj_lessons/(?P<resource_id>\w+)/$'],
    #  lesson.lesson_handler.dispatch),
    # 
    (r'^setting/$', setting.handler.dispatch),
    (r'^pay/$', mix_pay_handler.dispatch),
    (r'^absorbed/$', absorbed.handler.dispatch),

]

mobile_addPreCheck(urlpatterns_api_agrs, mobile_CheckUserForApiCaller, ut=[
    USER_LEVEL.LEVEL_NORMAL, USER_LEVEL.LEVEL_SHENG, USER_LEVEL.LEVEL_SHI, USER_LEVEL.LEVEL_QU,
    USER_LEVEL.LEVEL_PLATINUM, USER_LEVEL.LEVEL_ENDORSEMENT, USER_LEVEL.LEVEL_OPERATOR, USER_LEVEL.LEVEL_SUPERUSER,
    USER_LEVEL.LEVEL_CLASSMASTER])

mobile_urlpatterns_arg = [

    # (r'^setting/$', setting.handler.dispatch),
    # (r'^order/$', order.handler.dispatch),
    # (r'^statistic/$', stats.handler.dispatch),
    # (r'^mobile/lesson/$', lesson.lesson_handler.dispatch),
    # (r'^mobile/question/$', question.question_handler.dispatch),
    # (r'^mobile/product_yjmemeber/$', product_yjmemeber.handler.dispatch),
    # (r'^mobile/integral/$', integral.handler.dispatch),
    # ([r'^mobile/yj_coupon/$',
    #   r'^mobile/yj_coupon/(?P<resource_id>\w+)/$'], coupon.handler.dispatch)
]

mobile_addPreCheck(mobile_urlpatterns_arg, mobile_CheckUserForApiCaller)
# 跨年小程序无需授权登录接口
applet_urlpatterns_api = [

]

urlpatterns = [

                  # url(r'^launcher$', version.handler.launcher),
                  # url(r'^register$', register.handler.dispatch),
                  # url(r'^login$', loginout.handler.login),
                  # url(r'^loginreq$', loginout.handler.loginReq),
                  # url(r'^logoutreq$', loginout.handler.logoutReq),

                  url(r'^mobile/login/$', loginout.handler.m_login),
                  url(r'^mobile/logout/$', loginout.handler.mlogout),
                  url(r'^absorbed/list/$', absorbed.handler.note_list),
                  url(r'^absorbed/note_detail/$', absorbed.handler.note_detail),
                  url(r'^absorbed/note_message/$', absorbed.handler.note_message),
                  url(r'^absorbed/record_click/$', absorbed.handler.record_click),
                  url(r'^absorbed/get_banner/$', absorbed.handler.get_banner),
                  # url(r'^mobile/register/$', mregister.handler.handle_register),

              ] + urlpatterns_api + mobile_urlpatterns_api + applet_urlpatterns_api
